/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bakenote.xml;

import bakenote.core.*;
import org.apache.pivot.collections.ArrayList;
import org.apache.pivot.collections.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * @author lello
 *         <p/>
 *         The reader should read the recipe from this format
 *         <p/>
 *         <recipe title="Ricetta di prova" author="lello" source="nessuna" tag="" type="pane">
 *         <uuid>...............<uuid>
 *         <formula title="Biga">
 *         <ingredient name="farina" amount="150" units="g" />
 *         <ingredient name="acqua "amount="150" units="g" />
 *         <ingredient name="lievito" amount="150" units="g" />
 *         </formula>
 *         <formula title="Impasto finale">
 *         <ingredient name="farina" amount="150" units="g" />
 *         <ingredient name="acqua "amount="150" units="g" />
 *         <ingredient name="lievito" amount="150" units="g" />
 *         </formula>
 *         <instructions>
 *         Mescolare tutto
 *         </instructions>
 *         </recipe>                                                                                                              recipe.addFormula();
 */
public class RecipeXMLReader {

    private RecipeXMLReader() {
    }

    public static List<Recipe> parseXML(File xmlFile) throws Exception {

        List<Recipe> recipeList = new ArrayList<Recipe>();

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
        Document document = docBuilder.parse(xmlFile);

        Element root = (Element) document.getElementsByTagName("recipebook").item(0);

        NodeList recipeNodeList = root.getElementsByTagName("recipe");
        for (int i = 0; i < recipeNodeList.getLength(); i++) {
            Element recipeElement = (Element) recipeNodeList.item(i);
            Recipe recipe = new Recipe();
            recipe.setUUID(recipeElement.getElementsByTagName("uuid").item(0).getTextContent());
            //System.out.println("uuid "+recipeElement.getElementsByTagName("uuid").item(0).getTextContent());
            recipe.setName(recipeElement.getAttribute("title"));
            recipe.setAuthor(recipeElement.getAttribute("author"));
            recipe.setSource(recipeElement.getAttribute("source"));
            recipe.setType(recipeElement.getAttribute("kind"));
            recipe.setRating(Integer.parseInt(recipeElement.getAttribute("rating")));
            recipe.setTag(recipeElement.getElementsByTagName("tag").item(0).getTextContent());

            NodeList formulaNodeList = recipeElement.getElementsByTagName("formula");
            for (int j = 0; j < formulaNodeList.getLength(); j++) {
                Element formulaElement = (Element) formulaNodeList.item(j);
                Formula formula = new Formula();
                formula.setName(formulaElement.getAttribute("name"));
                NodeList ingredientNodeList = formulaElement.getElementsByTagName("ingredient");
                for (int k = 0; k < ingredientNodeList.getLength(); k++) {
                    Element ing = (Element) ingredientNodeList.item(k);
                    Ingredient ingredient = new Ingredient(ing.getAttribute("name"), ing.getAttribute("amount"), ing.getAttribute("unit"));
                    formula.addIngredient(ingredient);
                }
                recipe.addFormula(formula);
            }


            Element procedureElement = (Element) recipeElement.getElementsByTagName("procedure").item(0);
            Procedure procedure = new Procedure();
            NodeList stepNodeList = procedureElement.getElementsByTagName("step");
            for (int n = 0; n < stepNodeList.getLength(); n++) {
                ElementalProcedure elementalProcedure = new ElementalProcedure();
                Element timeElement = (Element) ((Element) stepNodeList.item(n)).getElementsByTagName("time").item(0);
                try {
                    elementalProcedure.setDuration(DatatypeFactory.newInstance().newDuration(timeElement.getTextContent()));
                } catch (DatatypeConfigurationException e1) {
                    System.out.println("cannot parse duration " + timeElement.getTextContent());
                }
                Element descriptionElement = (Element) ((Element) stepNodeList.item(n)).getElementsByTagName("description").item(0);
                elementalProcedure.setDescription(descriptionElement.getTextContent());
                procedure.add(elementalProcedure);
            }
            recipe.setProcedure(procedure);
            recipeList.add(recipe);
        }

        return recipeList;
    }

    /**
    public static List<Recipe> readXML(File xmlFile) throws Exception {

        List<Recipe> recipeList = new ArrayList<Recipe>();

        XMLSerializer xmlSerializer = new XMLSerializer();

        FileInputStream fileInputStream = new FileInputStream(xmlFile);
        Element element = xmlSerializer.readObject(fileInputStream);

        Element root = element.getElements("recipebook").get(0);

        for (Element recipeElement : root.getElements("recipes")) {
            Recipe recipe = new Recipe();
            recipe.setUUID(recipeElement.getElements("uuid").get(0).getText());
            recipe.setName(recipeElement.get("title"));
            recipe.setAuthor(recipeElement.get("author"));
            recipe.setSource(recipeElement.get("source"));
            recipe.setType(recipeElement.get("kind"));
            recipe.setRating(Integer.parseInt(recipeElement.get("rating")));
            recipe.setTag(recipeElement.getElements("tag").get(0).getText());

            for (Element p : recipeElement.getElements("formula")) {
                Formula formula = new Formula();
                for (Element i : p.getElements("ingredient")) {
                    Ingredient ingredient = new Ingredient(i.get("name"), i.get("amount"), i.get("unit"));
                    formula.addIngredient(ingredient);
                }
                recipe.addFormula(formula);
            }

            Element procedureElement = recipeElement.getElements("procedure").get(0);
            Procedure procedure = new Procedure();
            for (Element e : procedureElement.getElements("step")) {
                ElementalProcedure elementalProcedure = new ElementalProcedure();
                Element timeElement = e.getElements("time").get(0);
                try {
                    elementalProcedure.setDuration(DatatypeFactory.newInstance().newDuration(timeElement.getText()));
                } catch (DatatypeConfigurationException e1) {
                    System.out.println("cannot parse duration " + timeElement.getText());
                }
                Element descriptionElement = e.getElements("description").get(0);
                elementalProcedure.setDescription(descriptionElement.getText());
                procedure.add(elementalProcedure);
            }
            recipe.setProcedure(procedure);
            recipeList.add(recipe);
        }

        return recipeList;
    }


    public static List<Recipe> readXML(String filename) throws Exception {

        File xmlFile = new File(filename);
        return readXML(xmlFile);

    }**/
}
